package front.common.action;

import java.io.IOException;
import java.net.URLEncoder;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class LoginFilter implements Filter {

	public void destroy() {

	}

	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain filterChain) throws IOException, ServletException {
		request.setCharacterEncoding("utf-8");
		response.setCharacterEncoding("utf-8");
		HttpServletRequest rq = (HttpServletRequest) request;
		HttpServletResponse rp = (HttpServletResponse) response;
		HttpSession session = rq.getSession();
		String path = rq.getServletPath();
		if (path.equals("/view") || path.equals("/view/")) {
			StringBuffer contextUrl = rq.getRequestURL();
			StringBuffer basePath = contextUrl.delete(
					contextUrl.length() - rq.getRequestURI().length(),
					contextUrl.length()).append(rq.getContextPath())
					.append("/");
			rp.sendRedirect(basePath + "view/welcome.action");
		} else if (path.equals("/view/member/reg.jsp")
				|| path.equals("/view/member/reg.action")
				|| path.equals("/view/member/regUser.action")
				|| path.equals("/view/member/checkUser.action")
				|| path.endsWith("/view/index.action")
				|| path.endsWith("/view/welcome.action")
				||path.startsWith("/view/member/loginSuccess.action")
				|| path.startsWith("/view/member/login.jsp")
				|| path.endsWith("memberlogin.action")
				|| path.equals("/view/member/loginOut.action")) {
			//session.setAttribute("returnUrl", "");
			filterChain.doFilter(request, response);
		}  else {
			if (path.startsWith("/view/cart")
					|| path.startsWith("/view/member/")) {
				String userName = (String) session.getAttribute("userName");
				// 验证用户登录
				if (null == userName) {
					StringBuffer contextUrl = rq.getRequestURL();
					String returnUrl;
					//判断是否带有参数
					if (rq.getQueryString() == null)
						returnUrl = contextUrl.toString();
					else
						returnUrl = contextUrl.toString() + "?"
								+ rq.getQueryString();
					StringBuffer basePath = contextUrl.delete(
							contextUrl.length() - rq.getRequestURI().length(),
							contextUrl.length()).append(rq.getContextPath())
							.append("/");
					rp.sendRedirect(basePath + "view/member/login.jsp?returnUrl="+URLEncoder.encode(returnUrl, "UTF-8"));
				} else {
					filterChain.doFilter(request, response);
				}
			} else {
				filterChain.doFilter(request, response);
			}
		}

	}

	public void init(FilterConfig arg0) throws ServletException {
		// TODO Auto-generated method stub

	}

}
